<template>
  <div style="width: 900px;">
    <el-form ref="form" :inline="true" :model="form" class="demo-form-inline" label-width="140px" :rules="rules" style="margin-top: 20px">
      <el-form-item label="公司名称" prop="enterpriseName">
        <el-input v-model="form.enterpriseName" style="width: 295px" placeholder="请输入公司名称" />
      </el-form-item>
      <el-form-item label="统一社会信息代码" prop="enterpriseCode">
        <el-input v-model="form.enterpriseCode" style="width: 295px" placeholder="请输入统一社会信息代码" />
      </el-form-item>

      <el-form-item label="企业法人" prop="legalRepresentative">
        <el-input v-model="form.legalRepresentative" style="width: 295px" placeholder="请输入企业法人" />
      </el-form-item>
      <el-form-item label="招聘联系人" prop="enterpriseContacts">
        <el-input v-model="form.enterpriseContacts" style="width: 295px" placeholder="请输入招聘联系人" />
      </el-form-item>
      <el-form-item label="联系电话" prop="enterpriseTel">
        <el-input v-model="form.enterpriseTel" style="width: 295px" placeholder="请输入联系电话" />
      </el-form-item>
      <el-form-item label="联系手机" prop="enterpriseMobile">
        <el-input v-model="form.enterpriseMobile" style="width: 295px" placeholder="请输入联系手机" />
      </el-form-item>
      <el-form-item label="电子邮箱" prop="enterpriseMail">
        <el-input v-model="form.enterpriseMail" style="width: 295px" placeholder="请输入邮箱" />
      </el-form-item>
      <el-form-item label="公司性质" prop="enterpriseNatureCode">
        <el-select v-model="form.enterpriseNatureCode" style="width: 295px" placeholder="请选择" @change="enterpriseNatureChange">
          <el-option
            v-for="item in enterpriseNature"
            :key="item.infoId"
            :label="item.infoName"
            :value="item.infoId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="公司规模" prop="enterpriseScaleCode">
        <el-select v-model="form.enterpriseScaleCode" style="width: 295px" placeholder="请选择" @change="enterpriseScaleChange">
          <el-option
            v-for="item in enterpriseScale"
            :key="item.infoId"
            :label="item.infoName"
            :value="item.infoId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label=" " />
      <el-form-item label="行业" prop="industryCode">
        <el-select v-model="form.industryCode" style="width: 240px" placeholder="请选择" @change="industryeChange">
          <el-option
            v-for="item in industry"
            :key="item.infoId"
            :label="item.infoName"
            :value="item.infoId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="" prop="industrySubCode">
        <el-select v-model="form.industrySubCode" style="width: 240px" placeholder="请选择" @change="industrySubChange">
          <el-option
            v-for="item in industrySub"
            :key="item.infoId"
            :label="item.infoName"
            :value="item.infoId"
          />
        </el-select>
      </el-form-item>
      <div>
        <el-form-item label="省市区" prop="provCode">
          <el-select v-model="form.provCode" style="width: 240px" placeholder="请选择" @change="provChange">
            <el-option
              v-for="item in prov"
              :key="item.provCode"
              :label="item.provName"
              :value="item.provCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="" prop="cityCode">
          <el-select v-model="form.cityCode" style="width: 240px" placeholder="请选择" @change="cityChange">
            <el-option
              v-for="item in city"
              :key="item.cityCode"
              :label="item.cityName"
              :value="item.cityCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="" prop="distCode">
          <el-select v-model="form.distCode" style="width: 235px" placeholder="请选择" @change="distChange">
            <el-option
              v-for="item in dist"
              :key="item.distCode"
              :label="item.distName"
              :value="item.distCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="公司所在地址" prop="enterpriseAddress">
          <el-input v-model="form.enterpriseAddress" style="width: 743px" placeholder="请输入公司所在地址" />
        </el-form-item>
        <el-form-item label="公司网址" prop="enterpriseUrl">
          <el-input v-model="form.enterpriseUrl" style="width: 743px" placeholder="请输入公司网址" />
        </el-form-item>
      </div>
      <el-form-item label="专精特新" prop="proCode">
        <el-select v-model="form.proCode" style="width: 295px" clearable placeholder="请选择" @change="proChange">
          <el-option value="" label="" />
          <el-option
            v-for="item in pro"
            :key="item.infoId"
            :label="item.infoName"
            :value="item.infoId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="企业简介" prop="enterpriseRemark">
        <el-card style="height: 810px;">
          <quill-editor ref="myQuillEditor1" v-model="form.enterpriseRemark" style="height: 700px;" :options="editorOption1" />
        </el-card>
        <!--        <el-input v-model="form.enterpriseRemark" type="textarea" :rows="5" style="width: 700px;" />-->
      </el-form-item>
      <el-form-item label="企业logo" prop="enterpriseLogo">
        <upload ref="upload" v-model="form.enterpriseLogo" imgwidth="120px" imgheight="120px" @uploadSuccess="uploadSuccess" />
      </el-form-item>
      <el-form-item label="营业执照扫描件上传" prop="enterpriseScan">
        <upload ref="upload2" v-model="form.enterpriseScan" imgwidth="238px" imgheight="360px" @uploadSuccess="uploadSuccess2" />
      </el-form-item>
      <el-form-item style="margin-left: 40%">
        <el-button style="margin-right: 50px" @click="onCancel">取消</el-button>
        <el-button :loading="loading" type="primary" @click="onSubmit('form')">提交</el-button>
      </el-form-item>
    </el-form>
    <upload class="box1" style="display: none" imgwidth="0px" imgheight="0px" @uploadSuccess="quillSuccess" />
  </div>
</template>

<script>
import { entFind, entSave } from '@/api/enterprise'
import { getDictionary, getProv, getCity, getDist } from '@/api/entDictionary'
import { getToken } from '@/utils/auth'
import Upload from '@/components/upload'
import Quill from 'quill'
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import imageResize from 'quill-image-resize-module'
Quill.register('modules/imageResize', imageResize)
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike', 'clean', 'blockquote', 'code-block'], // toggled buttons
  [{ 'header': 1 }, { 'header': 2 }],
  [{ 'indent': '-1' }, { 'indent': '+1' }],
  [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
  [{ 'color': [] }, { 'background': [] }], [{ 'align': [] }],
  ['link', 'image']
]
export default {
  components: {
    quillEditor,
    Upload
  },
  data() {
    const validateEmail = (rule, value, callback) => {
      // const regEmail = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      const regEmail = /^[a-z0-9]+([._\\-]*[a-z0-9])+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (value.length < 1) {
        callback(new Error('请输入邮箱'))
      } else if (!regEmail.test(value)) {
        callback(new Error('请输入正确邮箱'))
      } else {
        callback()
      }
    }
    return {
      formInline: {
        user: '',
        region: ''
      },
      loading: false,
      enterpriseNature: [],
      industry: [],
      industrySub: [],
      enterpriseScale: [],
      pro: [],
      prov: [],
      city: [],
      dist: [],
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      fileList: [],
      uploadData: { id: 'sme03' },
      myHeaders: { 'Authorization': getToken() },
      uploadaction: process.env.VUE_APP_BASE_API + '/file/upload/img',
      uploadaccept: '.jpg,.jpeg,.png,.gif,.bmp,.pdf,.JPG,.JPEG,.PBG,.GIF,.BMP,.PDF',
      uploadlimit: 2,
      editorOption1: {
        placeholder: '',
        theme: 'snow',
        modules: {
          clipboard: {
            // 粘贴版，处理粘贴时候的自带样式
            matchers: [[Node.ELEMENT_NODE, this.onMatcher]]
          },
          imageResize: { // 添加
            displayStyles: { // 添加
              backgroundColor: 'black',
              border: 'none',
              color: 'white'
            },
            modules: ['Resize', 'DisplaySize', 'Toolbar'] // 添加
          },
          toolbar: {
            container: toolbarOptions,
            handlers: {
              'image': function(value) {
                if (value) {
                  document.querySelector(".box1 input[name='file']").click()
                } else {
                  this.quill.format('image', false)
                }
              }
            }
          }
        }
      },
      form: {
        id: '',
        enterpriseLogo: null,
        enterpriseName: '',
        enterpriseCode: '',
        enterpriseNatureCode: '',
        enterpriseNatureName: '',
        industryCode: '',
        industryName: '',
        industrySubCode: '',
        industrySubName: '',
        provCode: '',
        provName: '',
        cityCode: '',
        cityName: '',
        distCode: '',
        distName: '',
        enterpriseScaleCode: '',
        enterpriseScaleName: '',
        enterpriseAddress: '',
        enterpriseUrl: '',
        legalRepresentative: null,
        enterpriseContacts: '',
        enterpriseTel: '',
        enterpriseMobile: null,
        enterpriseMail: '',
        enterpriseRemark: '',
        enterpriseScan: null,
        proCode: '',
        proName: '',
        hotFalg: ''
      },
      rules: {
        enterpriseName: [
          { required: true, message: '请输入企业名称', trigger: 'blur' },
          { max: 30, message: '企业名称不得超过30字', trigger: 'blur' }
        ],
        enterpriseCode: [
          { required: true, message: '请输入统一社会信息代码', trigger: 'blur' },
          { min: 18, max: 18, message: '请输入正确的统一社会信息代码', trigger: 'blur' }
        ],
        legalRepresentative: [
          { required: true, message: '请输入法定代表人', trigger: 'blur' },
          { min: 2, max: 20, message: '法定代表人不得超过20字', trigger: 'blur' }
        ],
        enterpriseContacts: [
          { required: true, message: '请输入招聘联系人', trigger: 'blur' },
          { min: 2, max: 20, message: '招聘联系人不得超过20字', trigger: 'blur' }
        ],
        enterpriseTel: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { min: 11, max: 30, message: '联系电话长度在11到30个字符', trigger: 'blur' }
        ],
        enterpriseMail: [
          { required: true, trigger: 'blur', validator: validateEmail }
        ],
        enterpriseNatureCode: [
          { required: true, message: '请选择公司性质', trigger: 'change' }
        ],
        industryCode: [
          { required: true, message: '请选择所属行业', trigger: 'change' }
        ],
        industrySubCode: [
          { required: true, message: '请选择所属行业', trigger: 'change' }
        ],
        enterpriseScaleCode: [
          { required: true, message: '请选择企业规模', trigger: 'change' }
        ],
        provCode: [
          { required: true, message: '请选择省', trigger: 'change' }
        ],
        cityCode: [
          { required: true, message: '请选择市', trigger: 'change' }
        ],
        distCode: [
          { required: true, message: '请选择区', trigger: 'change' }
        ],
        enterpriseAddress: [
          { required: true, message: '请输入企业地址', trigger: 'blur' },
          { min: 2, max: 50, message: '企业地址不得超过50字', trigger: 'blur' }
        ],
        enterpriseRemark: [
          { required: true, message: '请输入企业说明', trigger: 'blur' },
          { min: 1, max: 8000, message: '企业说明长度在1到8000个字', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    const that = this
    // 公司性质
    const data = { parentId: 'CS03000016' }
    getDictionary(data).then(response => {
      if (response.result === 1) {
        that.enterpriseNature = response.data
      }
    })
    // 专精特新
    const data3 = { parentId: 'CS03010012' }
    getDictionary(data3).then(response => {
      if (response.result === 1) {
        that.pro = response.data
      }
    })
    // 行业一级
    const data1 = { parentId: 'CS03000036' }
    getDictionary(data1).then(response => {
      if (response.result === 1) {
        that.industry = response.data
      }
    })
    // 企业规模
    const data2 = { parentId: 'CS03000011' }
    getDictionary(data2).then(response => {
      if (response.result === 1) {
        that.enterpriseScale = response.data
      }
    })
    getProv().then(response => {
      if (response.result === 1) {
        that.prov = response.data
      }
    })
    entFind(this.$route.query).then(response => {
      console.log(response)
      if (response.result === 1) {
        that.form.id = response.data.id
        that.form.enterpriseName = response.data.enterpriseName
        that.form.enterpriseCode = response.data.enterpriseCode
        that.form.enterpriseNatureCode = response.data.enterpriseNatureCode
        that.form.enterpriseNatureName = response.data.enterpriseNatureName
        that.form.industryCode = response.data.industryCode
        that.form.industryName = response.data.industryName
        that.form.industrySubCode = response.data.industrySubCode
        that.form.industrySubName = response.data.industrySubName
        that.form.provCode = response.data.provCode
        that.form.provName = response.data.provName
        that.form.cityCode = response.data.cityCode
        that.form.cityName = response.data.cityName
        that.form.distCode = response.data.distCode
        that.form.distName = response.data.distName
        that.form.enterpriseScaleCode = response.data.enterpriseScaleCode
        that.form.enterpriseScaleName = response.data.enterpriseScaleName
        that.form.enterpriseAddress = response.data.enterpriseAddress
        that.form.enterpriseUrl = response.data.enterpriseUrl
        that.form.legalRepresentative = response.data.legalRepresentative
        that.form.enterpriseContacts = response.data.enterpriseContacts
        that.form.enterpriseTel = response.data.enterpriseTel
        that.form.enterpriseMobile = response.data.enterpriseMobile
        that.form.enterpriseMail = response.data.enterpriseMail
        that.form.enterpriseRemark = response.data.enterpriseRemark
        that.form.proCode = response.data.proCode
        that.form.proName = response.data.proName
        if (response.data.hotFlag !== undefined) {
          that.hotFalg = response.data.hotFlag
          if (response.data.hotFlag === '0' || response.data.hotFlag === '' || response.data.hotFlag === undefined || response.data.hotFlag === null) {
            const box = document.getElementsByClassName('ql-image')
            box[0].style.display = 'none'
            // that.$set(that.editorOption1.modules, 'clipboard', { matchers: [[Node.ELEMENT_NODE, this.onMatcher]] })
            // console.log(that.editorOption1)
            // this.$forceUpdate()
          }
        }
        if (response.data.enterpriseLogo !== undefined) {
          that.form.enterpriseLogo = response.data.enterpriseLogo
          this.$refs.upload.change(this.form.enterpriseLogo)
        }
        if (response.data.enterpriseScan !== undefined) {
          that.form.enterpriseScan = response.data.enterpriseScan
          this.$refs.upload2.change(this.form.enterpriseScan)
        }
        getDictionary({ parentId: that.form.industryCode }).then(response => {
          if (response.result === 1) {
            that.industrySub = response.data
          }
        })
        getCity({ provCode: that.form.provCode }).then(response => {
          if (response.result === 1) {
            that.city = response.data
          }
        })
        getDist({ cityCode: that.form.cityCode }).then(response => {
          if (response.result === 1) {
            that.dist = response.data
          }
        })
      }
    })
  },
  methods: {
    onSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading = true
          const that = this
          entSave(that.form).then(response => {
            if (response.result === 1) {
              that.$message({
                message: '修改成功', type: 'success'
              })
              this.$router.push('entUser')
            } else {
              that.$message({
                message: '修改失败', type: 'warning'
              })
            }
            this.loading = false
          })
        } else {
          return false
        }
      })
    },
    onCancel() {
      this.$router.push({ name: 'entUser' })
    },
    enterpriseNatureChange(val) {
      let obj = {}
      obj = this.enterpriseNature.find((item) => {
        return item.infoId === val
      })
      this.form.enterpriseNatureName = obj.infoName
    },
    proChange(val) {
      let obj = {}
      if (val === '') {
        this.form.proCode = ''
        this.form.proName = ''
      } else {
        obj = this.pro.find((item) => {
          return item.infoId === val
        })
        this.form.proName = obj.infoName
      }
    },
    industryeChange(val) {
      const that = this
      const data = { parentId: that.form.industryCode }
      that.form.industrySubCode = ''
      that.form.industrySubName = ''
      getDictionary(data).then(response => {
        if (response.result === 1) {
          that.industrySub = response.data
        }
      })
      let obj = {}
      obj = this.industry.find((item) => {
        return item.infoId === val
      })
      this.form.industryName = obj.infoName
    },
    industrySubChange(val) {
      let obj = {}
      obj = this.industrySub.find((item) => {
        return item.infoId === val
      })
      this.form.industrySubName = obj.infoName
    },
    enterpriseScaleChange(val) {
      let obj = {}
      obj = this.enterpriseScale.find((item) => {
        return item.infoId === val
      })
      this.form.enterpriseScaleName = obj.infoName
    },
    provChange(val) {
      const that = this
      that.form.cityCode = ''
      that.form.cityName = ''
      that.form.distCode = ''
      that.form.distName = ''
      getCity({ provCode: that.form.provCode }).then(response => {
        if (response.result === 1) {
          that.city = response.data
        }
      })
      let obj = {}
      obj = this.prov.find((item) => {
        return item.provCode === val
      })
      that.form.provName = obj.provName
    },
    cityChange(val) {
      const that = this
      that.form.distCode = ''
      that.form.distName = ''
      getDist({ cityCode: that.form.cityCode }).then(response => {
        if (response.result === 1) {
          that.dist = response.data
        }
      })
      let obj = {}
      obj = this.city.find((item) => {
        return item.cityCode === val
      })
      this.form.cityName = obj.cityName
    },
    distChange(val) {
      let obj = {}
      obj = this.dist.find((item) => {
        return item.distCode === val
      })
      this.form.distName = obj.distName
    },
    beforeAvatarUpload() {},
    uploadSuccess(val) {
      this.form.enterpriseLogo = val
    },
    uploadSuccess2(val) {
      this.form.enterpriseScan = val
    },
    handleChange(file) {
    },
    handleRemove(file) {
      this.$refs.upload.clearFiles()
    },
    handlePictureCardPreview(file) {
      console.log(getToken())
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleDownload(file) {
    },
    quillSuccess(val) {
      const that = this
      // 获取富文本组件实例
      const quill = that.$refs.myQuillEditor1.quill
      // 如果上传成功
      const res = process.env.VUE_APP_BASE_API + val
      if (res) {
        // 获取光标所在位置
        const length = quill.getSelection(true).index
        // 插入图片，res为服务器返回的图片链接地址
        quill.insertEmbed(length, 'image', res)
        // 调整光标到最后
        quill.setSelection(length + 1)
      } else {
        // 提示信息，需引入Message
      }
    },
    onMatcher(node, Delta) {
      const ops = []
      Delta.ops.forEach(op => {
        if (this.hotFalg !== '1') {
          if (op.insert) {
            if (typeof op.insert === 'string' || op.insert.image.indexOf('/pub/innovation/img') !== -1) { // 如果粘贴了图片，这里会是一个对象，所以可以这样处理
              ops.push({
                insert: op.insert, // 文字内容
                attributes: op.attributes // 文字样式（包括背景色和文字颜色等）
              })
            } else {
              alert('不允许粘贴图片')
            }
          }
        } else {
          ops.push({
            insert: op.insert, // 文字内容
            attributes: op.attributes // 文字样式（包括背景色和文字颜色等）
          })
        }
      })
      Delta.ops = ops
      return Delta
    }
  }
}
</script>

<style>
  .line{
    text-align: center;
  }
  .bordershow{
    border: 1px #cccccc solid;
    min-height: 360px;width: 238px;
    display: flex;align-items: center;}
  .avatar-uploader-icon {
    border: 1px #cccccc dotted;
    font-size: 28px;
    color: #8c939d;
    width: 238px;
    height: 360px;
    line-height: 360px;
    text-align: center;
  }
  .avatar {
    width: 232px;
    display: block;
    align-items: center;
  }
  .jl li{
    margin-right: 4px;
  }
  .jl .csa .el-form-item__content{
    position: inherit;
  }
</style>
